package cn.yh.register.msm.service.impl;

import cn.yh.register.msm.service.MsmService;
import cn.yh.register.msm.util.ConstantPropertiesUtils;
import cn.yh.register.vo.msm.MsmVo;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class MsmServiceImpl implements MsmService {

    /**
     * 发送验证码
     * @param phone 手机号
     * @param code 验证码
     * @return 验证码
     */
    @Override
    public Boolean send(String phone, String code) {
        Map<String,Object> map = new HashMap<>();
        map.put("code",code);
        return this.send(phone, map);
    }

    /**
     * 短信服务发送预约成功短信
     *
     * @param msmVo 发送对象
     * @return 是否成功
     */
    @Override
    public Boolean send(MsmVo msmVo) {
        return this.send(msmVo.getPhone(), msmVo.getParam());
    }


    /**
     * 封装的短信服务方法
     * @param phone 手机号
     * @param param 封装param对象
     * @return 是否成功
     */
    private Boolean send(String phone,Map<String,Object>param){
        //配置
        DefaultProfile profile = DefaultProfile.getProfile(
                ConstantPropertiesUtils.REGION_Id,
                ConstantPropertiesUtils.ACCESS_KEY_ID,
                ConstantPropertiesUtils.SECRECT
        );
        //客户端对象
        IAcsClient client = new DefaultAcsClient(profile);
        //发送短信的请求对象
        SendSmsRequest request = new SendSmsRequest();
        //签名名称
        request.setSignName("阿里云短息测试");
        //模板code
        request.setTemplateCode("SMS_154950909");
        //手机号
        request.setPhoneNumbers(phone);
        //内容
        request.setTemplateParam(JSONObject.toJSONString(param));
        //发送短信
        try {
            // 发送短信
            SendSmsResponse response = client.getAcsResponse(request);
            System.out.println(new Gson().toJson(response));
            if (response.getCode().equals("OK")){

            }
            System.out.println("已向手机号："+phone+"发送信息:"+param);
            return true;
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
        return false;
    }
}
